package cn.mengfly.testnrz.util;

import cn.mengfly.testnrz.nio.NioDemoConfig;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class SimpleTcpClient {

    public void send() {
        SocketChannel sc = null;

        try {
            sc = SocketChannel.open();
            sc.socket().connect(new InetSocketAddress(NioDemoConfig.SOCKET_IP, NioDemoConfig.SOCKET_PORT));
            sc.configureBlocking(false);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            Scanner scanner = new Scanner(System.in);
            System.out.println("连接成功，发送信息");
            while (scanner.hasNext()) {
                String next = scanner.next();
                byteBuffer.put(next.getBytes());
                byteBuffer.flip();
                sc.write(byteBuffer);
                byteBuffer.clear();
                System.out.println("消息发送:" + next);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭连接");
            IOUtil.close(sc);
        }
    }

    public static void main(String[] args) {
        new SimpleTcpClient().send();
    }
}
